/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * LoanComputer.java
 *
 * Created on 18/06/2011, 07:17:00 PM
 */

package GUI.ATTENDANT;

import GUI.Customer.Monitor;
import GUI.Customer.Server;
import Procedures.DBConection;
import Procedures.LoanTable;
import entities.Loan;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import javax.swing.JOptionPane;
import javax.swing.Timer;

/**
 *
 * @author SIX-14
 */
public class LoanComputerAutomatic extends javax.swing.JFrame {

    /** Creates new form LoanComputer */
    public LoanComputerAutomatic() {
    }
    public LoanComputerAutomatic(DBConection myConection, LoanTable loanTable, Server server) {
        initComponents();
        this.loanTable=loanTable;
        setMyConection(myConection);
        timer.start();
        setServer(server);
    }
    private DBConection myConection;
    private LoanTable loanTable;
    private Server server;
    private Monitor monitor;
    private Loan loan;

    public Loan getLoan() {
        return loan;
    }

    public void setLoan(Loan loan) {
        this.loan = loan;
    }

    public Monitor getMonitor() {
        return monitor;
    }

    public void setMonitor(Monitor monitor) {
        this.monitor = monitor;
    }



    public Server getServer() {
        return server;
    }

    public void setServer(Server server) {
        this.server = server;
    }


    public Timer timer  = new Timer (500, new ActionListener ()
    {
    public void actionPerformed(ActionEvent e)
    {
        if(jTextField1.getText().length()>4){
            loanComputer(jTextField1.getText());
            jTextField1.setText("");
        }
            // Aquí el código que queramos ejecutar.
     }
});

    public DBConection getMyConection() {
        return myConection;
    }

    public void setMyConection(DBConection myConection) {
        this.myConection = myConection;
    }

    public LoanTable getLoanTable() {
        return loanTable;
    }

    public void setLoanTable(LoanTable loanTable) {
        this.loanTable = loanTable;
    }




public void loanComputer(String id){
    boolean removetoken=false;
    int numberComputer=0;
    String computerRoom=null;
    String ip=null;
    for(int i=0; i<getLoanTable().getTable().length; i++){
        if(getLoanTable().getTable()[i].getId()==Integer.parseInt(jTextField1.getText())&&getLoanTable().getTable()[i].getType_user().equals("Alumno")){
            numberComputer=getLoanTable().getTable()[i].getNumberComputer();
            computerRoom=getLoanTable().getTable()[i].getComputerRoom();
            removetoken=true;
            ip=getLoanTable().getTable()[i].getIpcomputer();
            break;
        }
    }
    if(removetoken){
        setLoan(getLoanTable().removeLoan(Integer.parseInt(jTextField1.getText()),"Alumno", computerRoom));
        getMyConection().sendSQL("UPDATE COMPUTER SET STATE=1 WHERE NUMBER="+numberComputer+";");
        setMonitor(getServer().getComstumer().receiveResult("/"+ip));
        String endTime=(Calendar.getInstance().get(Calendar.HOUR_OF_DAY)+":"+Calendar.getInstance().get(Calendar.MINUTE)+":"+Calendar.getInstance().get(Calendar.SECOND));
        getMyConection().sendSQL("INSERT INTO LOAN_COMPUTER SET DATE='"+getLoan().getDate()+"', ID_USER="+getLoan().getId()+", NUMBER_COMPUTER="+getLoan().getNumberComputer()+", STARTTIME='"+getLoan().getStartTime()+"', ENDTIME='"+endTime+"', DURATION="+getMonitor().getDuration()+";");
        for(int i=0; i<getMonitor().getProcess().length; i++){
            if(getMonitor().getProcess()[i].getDuration()>0)
            getMyConection().sendSQL("INSERT INTO LOAN_COMPUTER_APLICATION SET COMPUTER="+getLoan().getNumberComputer()+", ID_USER="+getLoan().getId()+", DATE='"+getLoan().getDate()+"', DURATION="+getMonitor().getProcess()[i].getDuration()+", APLICATION='"+getMonitor().getProcess()[i].getName()+"';");
        }
        
        JOptionPane.showMessageDialog(null, "computadora Numero "+numberComputer+" liberada ", "Liberada", 1);
    }else{
    getMyConection().sendSQLQuery("SELECT active FROM STUDENT WHERE ID="+id+";");
    if(getMyConection().getLastResultSetColumnStrings(1)!=null){
        if(Boolean.parseBoolean(getMyConection().getLastResultSetColumnStrings(1)[0])){
            String number=nextcomputer();
            getMyConection().sendSQL("UPDATE COMPUTER SET STATE=5 WHERE NUMBER="+number+";");
            getMyConection().sendSQLQuery("SELECT IP FROM COMPUTER WHERE NUMBER="+number+";");
            ip= getMyConection().getLastResultSetColumnStrings(1)[0];
            getMyConection().sendSQLQuery("SELECT ID FROM APLICATION;");
            String[] process=getMyConection().getLastResultSetColumnStrings(1);
            getServer().getComstumer().beginMonitorCostumer("/"+ip, process);

            JOptionPane.showMessageDialog(null, "la computadora asignada es la "+number, "Computadora Asignada", 1);
        }else{
            JOptionPane.showMessageDialog(null, "Alumno esta dado de baja ", " Alumno estado baja ", 1);
        }
    }else{
        JOptionPane.showMessageDialog(null, "Usuario no esta regsitrado ", " Alumno no registrado ", 1);
    }
    }

}

public String nextcomputer(){
    getMyConection().sendSQLQuery("SELECT NUMBER, IP, LETTERCOMPUTERROOM FROM COMPUTER WHERE STATE=1;");
    String number=getMyConection().getLastResultSetColumnStrings(1)[0];
    System.out.println(number);
    String ip=getMyConection().getLastResultSetColumnStrings(2)[0];
    System.out.println(ip);
    String computerRoom=getMyConection().getLastResultSetColumnStrings(2)[0];
    System.out.println(computerRoom);
    getLoanTable().addLoan(Integer.parseInt(jTextField1.getText()), "Alumno",computerRoom, ip, Integer.parseInt(number));
    System.out.println();

    return number;
}

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTextField1 = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 116, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(274, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(45, 45, 45)
                .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(235, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents



    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new LoanComputerAutomatic().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables

}
